package com._520it.day2._04_returnpk;

import static org.junit.Assert.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import org.junit.Test;

import com._520it.util.JdbcUtil;

//  获取自动生成的主键
public class ReturnPkTest {

	@Test
	public void testStatement() throws Exception {
		Connection conn = JdbcUtil.getConn();
		Statement st = conn.createStatement();
		String sql="INSERT INTO account (name) VALUES('A')";
		st.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
		ResultSet rs = st.getGeneratedKeys();
		if (rs.next()) {
			long id = rs.getLong(1);//获取第一列
			System.out.println(id);
		}
		JdbcUtil.close(conn, st, rs);
	}
	
	@Test
	public void testPreparedStatement() throws Exception {
		String sql="INSERT INTO account (name) VALUES(?)";
		Connection conn = JdbcUtil.getConn();
		PreparedStatement ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
		ps.setString(1, "B");
		ps.executeUpdate();
		ResultSet rs = ps.getGeneratedKeys();
		if (rs.next()) {
			long id = rs.getLong(1);//获取第一列
			System.out.println(id);
		}
		JdbcUtil.close(conn, ps, rs);
	}
}
